﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Sharp.DataTransferObject;
using Sharp.Infrastructure.Communication;
using Sharp.Platform.Mvc.Models;
using Sharp.ServiceContracts;
using Sharp.WebBooter.Areas.CMS.Models;

namespace Sharp.WebBooter.Areas.CMS.Controllers
{
    public class PermissionController : Controller
    {

        public ActionResult Index(string owner, Guid ownerId)
        {
            using (var proxy = new ServiceProxy<IUserService>())
            {
                var model = new PermissionViewModel
                {
                    Owner = Request.Params["owner"],
                    OwnerId = Request.Params["ownerId"],
                    TreeNodes = new zTreeNode()
                };
                var list = proxy.Channel.AllPermissions();
                IEnumerable<PermissionDTO> selectedList;
                if (owner == "user")
                {
                    selectedList = proxy.Channel.GetPermissionById(ownerId);
                }
                else
                {
                    selectedList = proxy.Channel.GetPermissionByGroupId(ownerId);
                }
                Build(list, selectedList, model.TreeNodes, null);
                return View(model);
            }
        }

        private void Build(IEnumerable<PermissionDTO> table, IEnumerable<PermissionDTO> selectedList, zTreeNode node,
            Guid? parentValue)
        {
            var rows = table.Where(x => x.ParentId == parentValue).OrderBy(x => x.OrderIndex);
            foreach (var row in rows)
            {
                var _node = new zTreeNode
                {
                    Name = row.Title,
                    Id = row.Id.ToString(),
                    ParentId = row.ParentId == null ? row.ParentId.ToString() : null,
                    Raw = row,
                    Checked = selectedList.Any(x => x.Id == row.Id)
                };

                node.Children.Add(_node);
                node.IsParent = node.Children.Any();

                Build(table, selectedList, _node, row.Id);
            }
        }

        public ActionResult Save(Guid[] permissionIds, string owner, Guid ownerId)
        {
            using (var proxy = new ServiceProxy<IUserService>())
            {
                var res = proxy.Channel.SavePermission(permissionIds, owner, ownerId);


                return this.JsonNet(res);
            }
        }
    }
}